package storage

import (
	"fmt"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io"
	"oss-api/boot"
	"time"
)

// AliYunStorage 阿里云OSS
type AliYunStorage struct {
	Bucket *oss.Bucket
}

func NewAliYunStorage() *AliYunStorage {
	storage := boot.Config.Storage.Cloud
	client, err := oss.New(storage.Endpoint, storage.AccessKeyId, storage.AccessKeySecret, oss.UseCname(storage.UseCname))
	if err != nil {
		panic(fmt.Sprintf("[oss-api] %s [ERROR] : 初始化存储源失败: %s\n", time.Now().Format("2006-01-02 15:04:05"), err))
	}
	// 获取存储空间。
	bucket, err := client.Bucket(storage.BucketName)
	if err != nil {
		panic(fmt.Sprintf("[oss-api] %s [ERROR] : 获取存储空间失败: %s\n", time.Now().Format("2006-01-02 15:04:05"), err))
	}
	fmt.Printf("[oss-api] %s [INFO] : 初始化存储源码配置完成\n", time.Now().Format("2006-01-02 15:04:05"))
	return &AliYunStorage{
		Bucket: bucket,
	}
}

func (a *AliYunStorage) CreateFolder(name string) (bool, error) {
	panic("implement me")
}

func (a *AliYunStorage) UploadFile(name string, reader io.Reader) (string, error) {
	err := a.Bucket.PutObject(name, reader)
	if err != nil {
		return "", err
	}
	err = a.Bucket.SetObjectACL(name, oss.ACLPublicRead)
	if err != nil {
		return "", err
	}
	return name, err
}

// DeleteResource 删除
func (a *AliYunStorage) DeleteResource(path ...string) error {
	_, err := a.Bucket.DeleteObjects(path)
	oss.DeleteObjectsQuiet(true)
	return err
}

func (a *AliYunStorage) SetResourcePerm(path string, state bool) error {
	if state {
		return a.Bucket.SetObjectACL(path, oss.ACLPublicRead)
	} else {
		return a.Bucket.SetObjectACL(path, oss.ACLPrivate)
	}
}
